<?php
/**
 * @copyright: ©2024 永州微聚商 网络科技有限公司
 * @link: https://www.weiJuyunke.com
 */
namespace app\api\controller;

use app\admin\model\SystemConfig;
use app\common\controller\AdminController;
use think\captcha\facade\Captcha;
use think\facade\Env;
use Firebase\JWT\JWT;
use think\facade\Db;
use think\Model;
use app\admin\model\SystemLoginRecord;
use app\admin\model\SystemUser;

/**
 * Class Login
 *
 * @package app\admin\controller
 */
class Login extends AdminController
{

    /**
     * 用户登录
     *
     * @return string
     * @throws \Exception
     */
    public function login()
    {
        try {
            if ($this->request->isPost()) {
                
                $post = $this->request->post();
                $rule = [
                    'username|用户名' => 'require',
                    'password|密码' => 'require'
                ];
                $this->validate($post, $rule);
                
                $record = [
                    'username' => $post['username'],
                    'os' => get_os(),
                    'device' => get_os(),
                    'browser' => get_broswer(),
                    'ip' => $this->request->ip(),
                    'tenant_id' => 0,
                    'create_time' => date('Y-m-d H:i:s', time()),
                    'update_time' => date('Y-m-d H:i:s', time())
                ];
                
                $loginRecord = new SystemLoginRecord();
                
                $admin = Db::name("system_user")->where("username", $post['username'])->find();
                
                if (empty($admin)) {
                    $record['login_type'] = 1;
                    $record['comments'] = '用户不存在';
                    $loginRecord->save($record);
                    $loginRecord->save($record);
                    return msg([], 1002, "用户不存在!");
                }
                
                if ($admin['tenant_id'] != 1) {
                    
                    $admin = Db::name("system_user")->where([
                        "username" => $post['username'],
                        "agency_domain" => $post['host']
                    ])->find();
                    
                    if (empty($admin)) {
                        $record['login_type'] = 1;
                        $record['comments'] = '用户不存在';
                        $loginRecord->save($record);
                        $loginRecord->save($record);
                        return msg([], 1002, "用户不存在!");
                    }
                }
                
                $record['tenant_id'] = $admin['tenant_id'];
                if ($admin['status'] == 1) {
                    $record['login_type'] = 1;
                    $record['comments'] = '账号冻结';
                    $loginRecord->save($record);
                    return msg([], 1004, "账号冻结!");
                }
                
                if ($admin['password'] != md5($post['password'])) {
                    $record['login_type'] = 1;
                    $record['comments'] = '密码错误';
                    $loginRecord->save($record);
                    return msg([], 1004, "密码错误!");
                }
                
                if ($admin['has_past'] == 2 && $admin['past_data'] < strtotime(date("Y-m-d"))) {
                    $record['login_type'] = 1;
                    $record['comments'] = '平台已过期';
                    $loginRecord->save($record);
                    return msg([], 1004, "平台已过期!");
                }
                
                if ($admin['tenant_id'] == 3) {
                    $agency_user = SystemUser::where("user_id", $admin['account_id'])->find();
                    
                    if (! empty($agency_user)) {
                        if ($agency_user['status'] == 1) {
                            return msg([], 1004, "账号冻结!");
                        }
                        if ($agency_user['has_past'] == 2 && $agency_user['past_data'] < strtotime(date("Y-m-d"))) {
                            return msg([], 1004, "平台已过期! ");
                        }
                    } else {
                        return msg([], 1002, "用户不存在!");
                    }
                }
                
                unset($admin['password']);
                $admin['expire_time'] = time() + 7200;
                $user_id = $admin['user_id'];
                
                session('admin', $admin);
                // 权限
                $token = signToken([
                    "uid" => $user_id,
                    "tenant_id" => $admin['tenant_id']
                ]);
                
                $menu = Db::name("system_role_menu")->alias("a")
                    ->leftJoin("system_menu b", "a.menu_id=b.menu_id")
                    ->field("b.*,
            b.menu_id menuId,
            b.parent_id parentId,
            b.menu_type menuType,
            b.sort_number sortNumber,
            b.tenant_id tenantId,
            b.update_time updateTime,
            b.create_time createTime,
            a.tenant_id tenantId
            ")
                    ->where("a.role_id", "in", function ($query) use($user_id) {
                    $query->name("system_user_role")
                        ->where("user_id", $user_id)
                        ->field("role_id");
                })
                    ->select();
                //
                
                $roles = Db::name("system_role")->alias("a")
                    ->field("a.*,a.role_id roleId,a.role_name roleName,a.role_code roleCode,a.tenant_id tenantId,a.create_time createTime,a.update_time updateTime")
                    ->where("a.role_id", 1)
                    ->select();
                
                $admin['authorities'] = $menu;
                $admin['roles'] = $roles;
                $admin['accountNonExpired'] = true;
                $admin['accountNonLocked'] = true;
                
                $record['login_type'] = 0;
                $record['comments'] = '登录成功';
                $loginRecord->save($record);
                
                return msg([
                    "access_token" => $token,
                    "user" => $admin
                ], 0, "请求成功");
            }
            
            return msg([], 1001, "请求方式错误!");
        } catch (\Exception $e) {
            return result(- 1, '异常' . $e->getLine() . "--->" . $e->getMessage(), $e->getTrace());
            exit();
        }
    }

    /**
     * 用户信息
     *
     * @return mixed
     */
    public function user()
    {
        $request = $this->request;
        $user_id = $request->_UID;
        
        $user = Db::name("system_user")->where("user_id", $user_id)->find();
        
        return msg($user, 0, "");
    }

    /**
     * 用户退出
     *
     * @return mixed
     */
    public function out()
    {
        $request = $this->request;
        $user_id = $request->_UID;
        $user = Db::name("system_user")->where("user_id", $user_id)->find();
        
        $record = [
            'username' => $user['username'],
            'os' => get_os(),
            'device' => get_os(),
            'browser' => get_broswer(),
            'ip' => $request->ip(),
            'login_type' => 2,
            'tenant_id' => 1,
            'create_time' => date('Y-m-d H:i:s', time()),
            'update_time' => date('Y-m-d H:i:s', time())
        ];
        
        $loginRecord = new SystemLoginRecord();
        $loginRecord->save($record);
        
        session('admin', null);
        $this->success('退出登录成功');
    }

    /**
     * 验证码
     *
     * @return \think\Response
     */
    public function captcha()
    {
        $c = Captcha::createApi();
        
        return msg($c, 0, "操作成功");
    }
}
